package com.purchase.ml.utils;

import com.purchase.ml.bean.sdk.IpayNewDto;
import com.purchase.ml.bean.sdk.IpayQueryDto;
import com.purchase.ml.consts.CommonConsts;
import com.purchase.ml.service.sdk.impl.Ipay88ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kyyang on 2021/3/2 21:38
 */
@Aspect
@Component
@Slf4j
public class SdkIpay88Utils {
    //后台URL
    private static String s_backendUrl;

    @Value("${dns.backend_url}")
    private String backendUrl;

    @PostConstruct
    public void getS_backendUrl(){
        s_backendUrl = this.backendUrl;
    }

    public static Map<String,String> doRequestToIpay88(IpayNewDto dto) throws NoSuchAlgorithmException {
        String  responseUrl = s_backendUrl + "/purchase/ipay88/reposenUrl"; //支付完成跳转我方地址
        String  backendUrl  = s_backendUrl + "/purchase/ipay88/callback";   //我方接收异步地址
        HashMap<String,String> requestMap = new HashMap<>();
        requestMap.put("MerchantCode", CommonConsts.MERCHANTCODE);
        requestMap.put("RefNo",dto.getRefNo());
        requestMap.put("Currency","MYR");
        requestMap.put("ProdDesc",dto.getProdDesc());
        requestMap.put("UserName",dto.getUserName());
        requestMap.put("UserEmail",dto.getUserEmail());
        requestMap.put("UserContact",dto.getUserContact());
//        requestMap.put("UserName","daizh");
//        requestMap.put("UserEmail","834669151@qq.com");
//        requestMap.put("UserContact","13260691763");
        requestMap.put("SignatureType","SHA256");
        requestMap.put("ResponseURL",responseUrl);
        requestMap.put("BackendURL",backendUrl);
        //计算加密
//        BigDecimal;保留两位小数转成千位
        BigDecimal amountDecimal  = dto.getAmount().multiply(new BigDecimal(100));
        Long amountLong = amountDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).longValue();

        requestMap.put("Amount",dto.getAmount().toString()); //两位小数
//        requestMap.put("Amount","1.00"); //两位小数
        String paramStr =  CommonConsts.MERCHANTKEY + CommonConsts.MERCHANTCODE + dto.getRefNo() + amountLong + "MYR";
        log.info("paramStr====={}",paramStr);
        String sign = SHA256.calculateSha256(paramStr);
        requestMap.put("Signature",sign);
        log.info("requestMap========={}",requestMap);
        //组织数据放入查询列表
        IpayQueryDto queryDto = new IpayQueryDto();
        queryDto.setAmount(dto.getAmount().toString());
        queryDto.setRefNo(dto.getRefNo());

        //返回数据不全；暂时只通过异步
//        Ipay88ServiceImpl obj = new Ipay88ServiceImpl();
//        obj.pushObjToRedisList(queryDto);

        return requestMap;
    }
}
